import json
import uuid
import datetime
from django.views import View
from django.db.models import Q
from django.shortcuts import render, HttpResponse
from django.utils.decorators import method_decorator
from django.core.paginator import PageNotAnInteger, Paginator, EmptyPage
from plugins.public import encryption
from plugins.public import page as pg
from apps.rbac import models as db_rabc
from apps.cmdb import models as db_asset
from apps.logs import models as db_log
from apps.rbac.extra_views import login_check, perms_check
from plugins.public import encryption,zabbix_api



class IndexView(View):
    """首页"""
    @method_decorator(login_check)  #登陆检测
    def dispatch(self, request, *args, **kwargs):
        return super(IndexView, self).dispatch(request, *args, **kwargs)

    def get(self, request):
        caption = "首页"
        is_superuser = request.session['is_superuser']
        username = request.session["username"]
        role_obj = db_rabc.Role.objects.get(id=request.session['role_id'])
        #如果是超级管理员，显示所有信息
        if is_superuser == "1":
            asset = db_asset.Asset.objects.all()
        else:
            asset = role_obj.asset.all()
        asset_count = asset.count()
        user_count = db_rabc.User.objects.all().count()

        try:
            #获取zabbix 当前告警信息
            zbx_url =  db_rabc.Dict.objects.get(dict_key="zbx_url").dict_val
            zbx_user =  db_rabc.Dict.objects.get(dict_key="zbx_user").dict_val
            zbx_passwd = db_rabc.Dict.objects.get(dict_key="zbx_passwd").dict_val
            ret = zabbix_api.get_problem(zbx_url, zbx_user, zbx_passwd)
            zabbix_problem = ret
            abnormal_count = len(zabbix_problem)
        except:
            zabbix_problem = []
            abnormal_count = 0

        # 任务日志
        today_str = datetime.datetime.now().strftime("%Y-%m-%d")

        # 用户日志
        if request.session['is_superuser'] == "1":
            userlog_obj = db_log.UserLog.objects.all().order_by("-create_time")[:10]
        else:
            userlog_obj = db_log.UserLog.objects.filter(user=username).order_by("-create_time")[:10]

        # 资产图
        group_obj = db_asset.AssetGroup.objects.all()
        asset_count = db_asset.Asset.objects.all().count()
        n = 0
        group_data = []
        data_info = []
        for i in group_obj:
            group_data.append(i.group_name)
            asset = i.asset_set.all()
            group_count = asset.count()
            n += group_count
            data_info.append({"value": group_count, "name": i.group_name})
        other_count = asset_count - n
        if other_count > 0:
            data_info.insert(0, {"value": other_count, "name": u"未分组"})
            group_data.insert(0, "未分组")

        request.session["abnormal_count"] = abnormal_count
        return render(request, "base/index.html", locals())


class UserView(View):
    """用户管理视图"""
    @method_decorator(login_check)
    @method_decorator(perms_check)
    def dispatch(self, request, *args, **kwargs):
        return super(UserView, self).dispatch(request, *args, **kwargs)

    def get(self, request, page=1):
        caption = "用户列表"
        if request.session['is_superuser'] == "1":
            db_obj = db_rabc.User.objects.all().order_by('id')
        else:
            username = request.session["username"]
            db_obj = db_rabc.User.objects.filter(username=username).order_by('id')

        if db_obj:
            pagesize = 15
            paginator = Paginator(db_obj, pagesize)
            currentPage = int(page)
            page_nums = paginator.num_pages
            page_list = pg.control(currentPage, page_nums)
            try:
                data_list = paginator.page(page)
            except PageNotAnInteger:
                data_list = paginator.page(1)
            except EmptyPage:
                data_list = paginator.page(paginator.num_pages)
        else:
            data_list = None
        role_list = db_rabc.Role.objects.all()
        return render(request, 'rbac/user_list.html', locals())

    def post(self, request):
        '''添加用户'''
        username = request.POST.get("username")
        nick_name = request.POST.get("nick_name")
        password = request.POST.get("password")
        is_superuser = request.POST.get("is_superuser")
        role_id = request.POST.get("role_id")
        str_key = db_rabc.Dict.objects.get(dict_key="ENCRYPT_KEY").dict_val
        # 加密密码
        try:
            pc = encryption.prpcrypt(str_key)
            en_password = pc.encrypt(password)
            user_obj = db_rabc.User(username=username, nick_name=nick_name, password=en_password, role_id=role_id,
                                    is_superuser=is_superuser)
            user_obj.save()
            ret = {"status": "True", "info": "添加成功"}
        except Exception as e:
            msg = "添加失败：\n%s" % e
            ret = {"status": "False", "info": msg}
        data = json.dumps(ret)
        return HttpResponse(data)

    def put(self, request):
        """修改用户"""
        req_info = eval(request.body.decode())
        user_id = req_info.get("user_id")
        username = req_info.get("username")
        nick_name = req_info.get("nick_name")
        is_superuser = req_info.get("is_superuser")
        role_id = req_info.get("role_id")
        action = req_info.get("action")
        if action:
            user_obj = db_rabc.User.objects.get(id=user_id)
            user_obj.username = username
            user_obj.nick_name = nick_name
            if request.session['is_superuser'] == "1":
                user_obj.is_superuser = is_superuser
            user_obj.role_id = role_id
            user_obj.save()
            ret = {"status": "True", "info": "已修改"}
            data = json.dumps(ret)
            return HttpResponse(data)
        else:
            """获取修改的用户信息"""
            user_obj = db_rabc.User.objects.get(id=user_id)
            data = {"username": user_obj.username, "nick_name": user_obj.nick_name, "role_id": user_obj.role_id,
                    "user_id": user_obj.id, "is_superuser": user_obj.is_superuser}
            ret = {"status": "True", "info": data}
            data = json.dumps(ret)
            return HttpResponse(data)

    def delete(self, request):
        user_info = eval(request.body.decode())
        user_id = user_info.get("user_id")
        db_rabc.User.objects.get(id=user_id).delete()
        ret = {"status": "True", "info": "已删除"}
        data = json.dumps(ret)
        return HttpResponse(data)


class RoleView(View):
    """角色管理视图"""

    @method_decorator(login_check)
    @method_decorator(perms_check)
    def dispatch(self, request, *args, **kwargs):
        return super(RoleView, self).dispatch(request, *args, **kwargs)

    def get(self, request, page=1):
        caption = "角色列表"
        db_obj = db_rabc.Role.objects.all().order_by('id')
        if db_obj:
            pagesize = 15
            paginator = Paginator(db_obj, pagesize)
            currentPage = int(page)
            page_nums = paginator.num_pages
            page_list = pg.control(currentPage, page_nums)
            try:
                data_list = paginator.page(page)
            except PageNotAnInteger:
                data_list = paginator.page(1)
            except EmptyPage:
                data_list = paginator.page(paginator.num_pages)
        else:
            data_list = None
        return render(request, 'rbac/role_list.html', locals())

    def post(self, request):
        '''添加角色'''
        title = request.POST.get("role")
        try:
            role_obj = db_rabc.Role(title=title)
            role_obj.save()
            ret = {"status": "True", "info": "添加成功"}
        except Exception as e:
            msg = "添加失败：\n%s" % e
            ret = {"status": "False", "info": msg}

        data = json.dumps(ret)
        return HttpResponse(data)

    def put(self, request):
        """修改角色"""
        role_info = eval(request.body.decode())
        role_id = role_info.get("role_id")
        role = role_info.get("role")
        action = role_info.get("action", None)
        if action:
            """修改角色信息"""
            role_obj = db_rabc.Role.objects.get(id=role_id)
            role_obj.title = role
            role_obj.save()
            ret = {"status": "True", "info": "已修改"}
            data = json.dumps(ret)
            return HttpResponse(data)
        else:
            """获取修改信息"""
            role_obj = db_rabc.Role.objects.get(id=role_id)
            info_json = {'role_id': role_obj.id, 'role': role_obj.title}
            ret = {"status": "True", "info": info_json}
            data = json.dumps(ret)
        return HttpResponse(data)

    def delete(self, request):
        role_info = eval(request.body.decode())
        role_id = role_info.get("role_id")
        db_rabc.Role.objects.get(id=role_id).delete()
        ret = {"status": "True", "info": "已删除"}
        data = json.dumps(ret)
        return HttpResponse(data)


class PermsView(View):
    """角色管理视图"""

    # @method_decorator(login_check)
    # @method_decorator(perms_check)
    def dispatch(self, request, *args, **kwargs):
        return super(PermsView, self).dispatch(request, *args, **kwargs)

    def get(self, request, page=1):
        caption = "权限列表"
        menus_list = db_obj = db_rabc.Permission.objects.filter(perms_type__contains="菜单").order_by('weight')
        db_obj = db_rabc.Permission.objects.all().order_by('id')
        one_perms = db_rabc.Permission.objects.filter(perms_type__contains="一级菜单").order_by('weight')
        perms_list = []
        for i in one_perms:
            one_child = []
            tow_perms = db_rabc.Permission.objects.filter(parent_id=i.id)
            for j in tow_perms:
                two_child = []
                three_perms = db_rabc.Permission.objects.filter(parent_id=j.id)
                for k in three_perms:
                    two_child.append({"id": k.id, "title": k.title, "perms_id": k.perms_id, "perms_icon": k.perms_icon,
                                      "url": k.url, "perms_method": k.perms_method, "perms_status": k.perms_status,
                                      "perms_type": k.perms_type})

                one_child.append({"id": j.id, "title": j.title, "perms_id": j.perms_id, "perms_icon": j.perms_icon,
                                  "url": j.url, "perms_method": j.perms_method, "perms_status": j.perms_status,
                                  "child": two_child, "perms_type": j.perms_type})

            perms_list.append({"id": i.id, "title": i.title, "perms_icon": i.perms_icon, "perms_id": i.perms_id,
                               "url": i.url, "perms_method": i.perms_method, "perms_status": i.perms_status,
                               "child": one_child, "perms_type": i.perms_type, "weight": i.weight})

        data_list = []
        if perms_list:
            pagesize = 1
            paginator = Paginator(perms_list, pagesize)
            currentPage = int(page)
            page_nums = paginator.num_pages
            page_list = pg.control(currentPage, page_nums)
            try:
                data_list = paginator.page(page)
            except PageNotAnInteger:
                data_list = paginator.page(1)
            except EmptyPage:
                data_list = paginator.page(paginator.num_pages)
        else:
            data_list = None
        return render(request, 'rbac/perms_list.html', locals())

    def post(self, request):
        """添加权限"""
        title = request.POST.get("title")
        perms_type = request.POST.get("perms_type")
        perms_method = request.POST.get("perms_method")
        perms_icon = request.POST.get("perms_icon")
        parent_id = request.POST.get("parent_id")
        url = request.POST.get("url")
        weight = request.POST.get("weight")
        uuid_str = "{}{}".format(url, perms_method)
        perms_id = uuid.uuid3(uuid.NAMESPACE_DNS, uuid_str)
        try:
            if parent_id != "top":
                perms_obj = db_rabc.Permission(title=title, perms_id=perms_id, perms_icon=perms_icon,
                                               perms_type=perms_type, parent_id=parent_id, url=url,
                                               perms_method=perms_method)
            else:
                perms_obj = db_rabc.Permission(title=title, perms_id=perms_id, perms_icon=perms_icon,
                                               perms_type=perms_type, url=url, perms_method=perms_method, weight=weight)
            perms_obj.save()

            ret = {"status": "True", "info": "添加成功"}
        except Exception as e:
            msg = "添加失败：\n%s" % e
            ret = {"status": "False", "info": msg}
        data = json.dumps(ret)
        return HttpResponse(data)

    def put(self, request):
        """修改权限"""
        req_info = eval(request.body.decode())
        perms_id = req_info.get("perms_id")
        title = req_info.get("title")
        perms_type = req_info.get("perms_type")
        perms_method = req_info.get("perms_method")
        perms_icon = req_info.get("perms_icon")
        parent_id = req_info.get("parent_id")
        url = req_info.get("url")
        weight = req_info.get("weight")
        action = req_info.get("action")
        if action:
            perms_obj = db_rabc.Permission.objects.get(id=perms_id)
            perms_obj.title = title
            perms_obj.perms_type = perms_type
            perms_obj.perms_icon = perms_icon
            perms_obj.perms_method = perms_method
            if weight:
                perms_obj.weight = weight
            if parent_id != "top":
                perms_obj.parent_id = parent_id
            else:
                perms_obj.parent_id = None
            perms_obj.url = url
            uuid_str = "{}{}".format(url, perms_method)
            perms_key = uuid.uuid3(uuid.NAMESPACE_DNS, uuid_str)
            perms_obj.perms_id = perms_key
            perms_obj.save()
            ret = {"status": "True", "info": "已修改"}
            data = json.dumps(ret)
            return HttpResponse(data)
        else:
            perms_obj = db_rabc.Permission.objects.get(id=perms_id)
            if perms_obj.parent_id:
                parent_id = perms_obj.parent_id
            else:
                parent_id = "top"

            data = {"perms_id": perms_obj.id, "title": perms_obj.title, "perms_type": perms_obj.perms_type,
                    "parent_id": parent_id, "url": perms_obj.url, "perms_icon": perms_obj.perms_icon,
                    "perms_method": perms_obj.perms_method, "weight": perms_obj.weight}

            ret = {"status": "True", "info": data}
            data = json.dumps(ret)
            return HttpResponse(data)

    def delete(self, request):
        """删除权限"""
        req_info = eval(request.body.decode())
        perms_id = req_info.get("perms_id")
        db_rabc.Permission.objects.get(id=perms_id).delete()
        ret = {"status": "True", "info": "已删除"}
        data = json.dumps(ret)
        return HttpResponse(data)


class DictView(View):
    """配置字典视图"""

    @method_decorator(login_check)
    @method_decorator(perms_check)
    def dispatch(self, request, *args, **kwargs):
        return super(DictView, self).dispatch(request, *args, **kwargs)

    def get(self, request, page=1):
        caption = "配置字典"
        db_obj = db_rabc.Dict.objects.all().order_by('dict_key')
        if db_obj:
            pagesize = 12
            paginator = Paginator(db_obj, pagesize)
            # 从前端获取当前的页码数,默认为1
            currentPage = int(page)
            page_nums = paginator.num_pages
            page_list = pg.control(currentPage, page_nums)
            try:
                data_list = paginator.page(page)  # 获取当前页码的记录
            except PageNotAnInteger:
                data_list = paginator.page(1)  # 如果用户输入的页码不是整数时,显示第1页的内容
            except EmptyPage:
                data_list = paginator.page(paginator.num_pages)
        else:
            data_list = None
        return render(request, 'rbac/dict_list.html', locals())

    def post(self, request):
        '''添加配置'''
        dict_key = request.POST.get("dict_key")
        dict_val = request.POST.get("dict_val")
        dict_msg = request.POST.get("dict_msg")
        try:
            dict_obj = db_rabc.Dict(dict_key=dict_key, dict_val=dict_val, dict_msg=dict_msg)
            dict_obj.save()
            ret = {"status": "True", "info": "添加成功"}
        except Exception as e:
            msg = "添加失败：\n%s" % e
            ret = {"status": "False", "info": msg}
        data = json.dumps(ret)
        return HttpResponse(data)

    def put(self, request):
        """修改配置"""
        dict_info = eval(request.body.decode())
        dict_id = dict_info.get("dict_id")
        dict_key = dict_info.get("dict_key")
        dict_val = dict_info.get("dict_val")
        dict_msg = dict_info.get("dict_msg")
        action = dict_info.get("action", None)
        if action:
            """修改角色信息"""
            dict_obj = db_rabc.Dict.objects.get(id=dict_id)
            dict_obj.dict_key = dict_key
            dict_obj.dict_val = dict_val
            dict_obj.dict_msg = dict_msg
            dict_obj.save()
            ret = {"status": "True", "info": "已修改"}
            data = json.dumps(ret)
            return HttpResponse(data)
        else:
            """获取修改信息"""
            dict_obj = db_rabc.Dict.objects.get(id=dict_id)
            info_json = {'dict_id': dict_obj.id, 'dict_key': dict_obj.dict_key, 'dict_val': dict_obj.dict_val,
                         'dict_msg': dict_obj.dict_msg}
            ret = {"status": "True", "info": info_json}
            data = json.dumps(ret)
        return HttpResponse(data)

    def delete(self, request):
        dict_info = eval(request.body.decode())
        dict_id = dict_info.get("dict_id")
        db_rabc.Dict.objects.get(id=dict_id).delete()
        ret = {"status": "True", "info": "已删除"}
        data = json.dumps(ret)
        return HttpResponse(data)
